Imports System.Collections.Generic
Imports Cdm.DataCore.LookupTables
Imports Cdm.DataCore.Budget


Partial Class BudgetOnlineEntry_SpendingPlanEntry
    Inherits System.Web.UI.Page


    'Private SpendingPlanRowList As Hashtable
    Private CategoryHeaderList As Hashtable
    Private FormulaList As ArrayList
    Private FormulaPairings As ArrayList
    Private JavaScriptList As ArrayList
    Private CategoryTotalCostFields As ArrayList
    Private CategoryTotalJavaScript As ArrayList
    Private SpendingPlanTotalFields As ArrayList
    Dim C_EDIT_EXISTING As String = "0"
    Dim C_COPY_AND_CREATE As String = "1"
    Dim C_CREATE_BLANK As String = "2"



    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'SpendingPlanRowList = New Hashtable()
        CancelButton.Attributes.Add("onclick", "CancelChanges();")
        If Not Me.IsPostBack Then
            JavaScriptList = New ArrayList()
            BindDropDowns()
            SetBudgetAndDateRowsVisible(False)

            Dim mm As MasterPageExpandable = Me.Master
            mm.HideHeader(False)
        End If
    End Sub

    Private Sub BindDropDowns()
        Dim participantId As Integer = EntityController.GetParticipant().ParticipantId

        Me.BudgetDropDownList.DataSource = Budget.ListAllbyParticipantId(participantId)
        Me.BudgetDropDownList.DataTextField = "BudgetDescription"
        Me.BudgetDropDownList.DataValueField = "BudgetId"
        Me.BudgetDropDownList.DataBind()

        Me.SpendingPlanDropDownList.DataSource = SpendingPlanGrid.ListByParticipant(participantId, "StartDate DESC")
        SpendingPlanDropDownList.DataTextField = "EffectiveDatesWithStatusAndVersion"
        SpendingPlanDropDownList.DataValueField = "SpendingPlanId"
        SpendingPlanDropDownList.DataBind()
        SpendingPlanDropDownList.Items.Insert(0, New ListItem("Blank", "0"))
    End Sub

    Protected Property SpendingPlanId() As Integer
        Get
            If ViewState("spendingplanid") Is Nothing Then
                Return 0
            Else
                Return CInt(ViewState("spendingplanid"))
            End If
        End Get
        Set(ByVal value As Integer)
            ViewState("spendingplanid") = value
        End Set
    End Property

    Private Sub RegisterJavaScript()
        Dim sb As New System.Text.StringBuilder()

        sb.AppendLine("<script language='javascript'>")
        sb.AppendLine("function UpdateCalcs()")
        sb.AppendLine("{")
        For iLine As Integer = 0 To JavaScriptList.Count - 1
            sb.AppendLine("     " + JavaScriptList(iLine) + ";")
        Next

        sb.AppendLine()
        sb.AppendLine("// Category Totals")
        For iCat As Integer = 0 To CategoryTotalJavaScript.Count - 1
            sb.AppendLine(CategoryTotalJavaScript(iCat))
        Next

        sb.AppendLine()
        sb.AppendLine("// Spending Plan Total")
        sb.AppendLine(GetJavaScriptSumStatement(Me.SpendingPlanTotalTextBox.ClientID, SpendingPlanTotalFields))
        sb.AppendLine()

        sb.AppendLine("}")
        sb.AppendLine("</script>")
        Me.javascriptLiteral.Text = sb.ToString()
    End Sub

    Private Sub WriteLine(ByVal line As String)
        Response.Write(line)
        Response.Write(Chr(13))
    End Sub

    Private Function GetCategoryHeader(ByVal headerId As Integer) As LuAdminBudgetCategoryHeader
        If CategoryHeaderList Is Nothing Then
            PopulateCategoryHeaderList()
        End If

        Return CategoryHeaderList(headerId)
    End Function

    Private Sub PopulateCategoryHeaderList()
        CategoryHeaderList = New Hashtable()
        Dim allHeaders As List(Of LuAdminBudgetCategoryHeader) = LuAdminBudgetCategoryHeader.ListAll()
        For i As Integer = 0 To allHeaders.Count - 1
            CategoryHeaderList.Add(allHeaders(i).BudgetCategoryHeaderId, allHeaders(i))
        Next
    End Sub
    Private Sub BindCategoryList()
        Dim categoryList As List(Of LuAdminBudgetCategory) = LuAdminBudgetCategory.ListForSpendingPlan()
        Me.CategoryDataList.DataSource = categoryList
        Me.CategoryDataList.DataBind()

        RegisterJavaScript()
        Page.RegisterStartupScript("onload", "<script language=""javascript"">UpdateCalcs();</script>")
        Dim detailsLabel As Label = Me.ResultsPane.FindControl("SpendingPlanDetailsLabel")
        If Not detailsLabel Is Nothing Then
            detailsLabel.Text = "Spending Plan Details for " + EntityController.GetParticipant().FullName
        End If
    End Sub

    Protected Sub CategoryDataList_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles CategoryDataList.ItemDataBound
        CategoryTotalCostFields = New ArrayList()
        Dim currentCategory As LuAdminBudgetCategory = e.Item.DataItem
        Dim rowRepeater As Repeater = e.Item.FindControl("CategoryRowsRepeater")
        Dim itemList As List(Of SpendingPlanItem) = SpendingPlanItem.ListByCategoryWithBlanks(Me.SpendingPlanId, currentCategory.BudgetCategoryId)
        Dim rowList As ArrayList

        If Not itemList Is Nothing Then
            rowList = AddItemsToRows(itemList)
            rowRepeater.DataSource = rowList
            rowRepeater.DataBind()
        End If

        Dim categoryTotalTextBox As TextBox = e.Item.FindControl("CategoryTotalTextBox")
        'Write Javascript Category Total

        If CategoryTotalJavaScript Is Nothing Then
            CategoryTotalJavaScript = New ArrayList()
            SpendingPlanTotalFields = New ArrayList()
        End If
        CategoryTotalJavaScript.Add(GetJavaScriptSumStatement(categoryTotalTextBox.ClientID, CategoryTotalCostFields))
        SpendingPlanTotalFields.Add(categoryTotalTextBox.ClientID)
    End Sub

    Private Function GetJavaScriptSumStatement(ByVal totalFieldClientId As String, ByVal ClientIdList As ArrayList) As String

        Dim statement As String = String.Concat("document.getElementById('", totalFieldClientId, "').value=MoneyValue(")
        Dim plusSign As String = ""

        For i As Integer = 0 To ClientIdList.Count - 1
            statement = String.Concat(statement, plusSign, "EvaluateValue(document.getElementById('", ClientIdList(i).ToString(), "').value)")
            plusSign = "+"
        Next

        statement = String.Concat(statement, ");")
        Return statement

    End Function

    Protected Sub CategoryRowsRepeater_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs)
        Dim rowItemsRepeater As Repeater = e.Item.FindControl("RowItemsRepeater")
        Dim currentRow As SpendingPlanRow = e.Item.DataItem
        rowItemsRepeater.DataSource = currentRow.ItemList
        rowItemsRepeater.DataBind()
    End Sub

    Protected Sub RowItemsRepeater_DataBinding(ByVal sender As Object, ByVal e As System.EventArgs) Handles CategoryDataList.DataBinding
        FormulaList = New ArrayList()
        FormulaPairings = New ArrayList()
        FormulaPairings.Add(New FormulaPairing("TaxRate", "0.11"))
        FormulaPairings.Add(New FormulaPairing("[TaxRate]", "0.11"))
        FormulaPairings.Add(New FormulaPairing("[DaysInSpendingPlan]", 120))
        FormulaPairings.Add(New FormulaPairing("DaysInSpendingPlan", 120))
    End Sub

    Protected Sub RowItemsRepeater_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs)
        Dim currentItem As SpendingPlanItem = e.Item.DataItem
        Dim currentHeader As LuAdminBudgetCategoryHeader = GetCategoryHeader(currentItem.BudgetCategoryHeaderId)
        Dim formulaDisplayName As String = String.Concat("[", currentHeader.DisplayName, "]")



        If e.Item.ItemIndex = 0 Then
            FormulaList.Add("//// Row " + currentItem.BudgetItemNumber.ToString())
        End If

        Dim currentTextBox As TextBox = e.Item.FindControl("ItemTextBox")
        Dim currentLabel As Label = e.Item.FindControl("ItemLabel")

        If currentItem.BudgetItemNumber = -1 Then
            'currentTextBox.Text = currentHeader.DisplayName
            'currentTextBox.BorderStyle = BorderStyle.None
            'currentTextBox.BackColor = Drawing.Color.LightGray
            ''currentTextBox.Columns = currentHeader.ColumnWidth
            'currentTextBox.TextMode = TextBoxMode.MultiLine
            'currentTextBox.Font.Size = FontUnit.Point(8)
            'currentTextBox.Rows = 2
            currentLabel.Visible = True
            currentTextBox.Visible = False
            currentLabel.Text = currentHeader.DisplayName
            currentTextBox.Columns = currentHeader.ColumnWidth
            currentLabel.Width = currentTextBox.Width
            Return
        End If

        Dim formulaClientId As String
        Dim align As String
        Select Case currentHeader.ItemFormat
            Case "integer", "decimal"
                formulaClientId = String.Concat(" parseFloat(document.getElementById('", currentTextBox.ClientID, "').value)")
                align = "right"
            Case "currency"
                formulaClientId = String.Concat(" parseFloat(document.getElementById('", currentTextBox.ClientID, "').value)")
                align = "right"
            Case Else
                formulaClientId = String.Concat(" document.getElementById('", currentTextBox.ClientID, "').value")
                align = "left"
        End Select

        If currentHeader.ItemFormat = "currency" Then
            currentLabel.Visible = True
            currentLabel.Text = "$"
        Else
            currentLabel.Visible = False
        End If

        AddValidator(currentItem, currentHeader, currentTextBox)

        FormulaPairings.Add(New FormulaPairing(formulaDisplayName, formulaClientId))
        If Not currentTextBox Is Nothing Then
            currentTextBox.Columns = currentHeader.ColumnWidth
            If currentHeader.Formula.Length > 0 Then
                'currentTextBox.Enabled = False
                currentTextBox.BackColor = Drawing.Color.Transparent
                currentTextBox.ForeColor = Drawing.Color.Black
                'currentTextBox.BorderStyle = BorderStyle.None
                currentTextBox.Style("text-align") = align
                Dim currentFormula As String
                If currentHeader.ItemFormat = "currency" Then
                    currentFormula = String.Concat(" document.getElementById('", currentTextBox.ClientID, "').value=MoneyValue(", currentHeader.Formula.Substring(1), ")")
                Else
                    currentFormula = String.Concat(" document.getElementById('", currentTextBox.ClientID, "').value=EvaluateValue(", currentHeader.Formula.Substring(1), ")")
                End If
                FormulaList.Add(currentFormula)
            Else
                currentTextBox.Enabled = True
                currentTextBox.Style("text-align") = align
                currentTextBox.BackColor = Drawing.Color.White
                currentTextBox.Attributes.Add("onchange", "UpdateCalcs()")
            End If
            If currentHeader.ItemFormat = "currency" Then
                currentTextBox.Text = currentTextBox.Text.Replace("$", "")
            End If
        End If

        If currentHeader.DisplayName = "Start Date" Then

        End If

        If currentHeader.IsTotalCostField Then
            AddJavaScriptStatements()
            CategoryTotalCostFields.Add(currentTextBox.ClientID)
        End If

    End Sub
    Private Sub AddValidator(ByVal itm As SpendingPlanItem, ByVal hdr As LuAdminBudgetCategoryHeader, _
                             ByVal txt As TextBox)

        Select Case hdr.ItemFormat.ToLower()
            Case "date"
                Dim cal As New AjaxControlToolkit.CalendarExtender
                cal.ID = "dtExtender"
                cal.TargetControlID = txt.ID
                txt.Parent.Controls.Add(cal)
            Case "decimal", "currency"
                Dim compareDecimal As New CustomValidator()
                compareDecimal.ID = "compare_decimal"
                compareDecimal.ClientValidationFunction = "ValidateDecimal"
                compareDecimal.ErrorMessage = "This number needs to be numeric."
                compareDecimal.ControlToValidate = txt.ID
                compareDecimal.Display = ValidatorDisplay.None
                txt.Parent.Controls.Add(compareDecimal)

                Dim vcoTwo As New AjaxControlToolkit.ValidatorCalloutExtender()
                vcoTwo.ID = "vcoDecimal"
                vcoTwo.TargetControlID = "compare_decimal"
                vcoTwo.Width = "200"
                txt.Parent.Controls.Add(vcoTwo)
            Case "integer"
                Dim compareInteger As New CustomValidator()
                compareInteger.ID = "compare_integer"
                compareInteger.ClientValidationFunction = "ValidateInteger"
                compareInteger.ErrorMessage = "This number needs to be an integer."
                compareInteger.ControlToValidate = txt.ID
                compareInteger.Display = ValidatorDisplay.None
                txt.Parent.Controls.Add(compareInteger)

                Dim vcoTwo As New AjaxControlToolkit.ValidatorCalloutExtender()
                vcoTwo.ID = "vcoInteger"
                vcoTwo.TargetControlID = "compare_integer"
                vcoTwo.Width = "200"
                txt.Parent.Controls.Add(vcoTwo)
            Case Else
                'text -do not validate
        End Select

        If hdr.DisplayName = "Item Code" Then
            Dim ItemCodeAutoComplete As New AjaxControlToolkit.AutoCompleteExtender
            ItemCodeAutoComplete.TargetControlID = txt.ID
            ItemCodeAutoComplete.ServicePath = "~/AJAX/AutoComplete.asmx"
            'ItemCodeAutoComplete.BehaviorID = "QuickSearchEx"
            ItemCodeAutoComplete.ServiceMethod = "GetItemCodes"
            ItemCodeAutoComplete.MinimumPrefixLength = 1
            ItemCodeAutoComplete.CompletionInterval = 50
            ItemCodeAutoComplete.CompletionSetCount = 10
            
            ItemCodeAutoComplete.CompletionListItemCssClass = "autocomplete_listItemSP"
            ItemCodeAutoComplete.CompletionListCssClass = "autocomplete_completionListElementSP"
            ItemCodeAutoComplete.CompletionListHighlightedItemCssClass = "autocomplete_highlightedListItemSP"

            txt.Parent.Controls.Add(ItemCodeAutoComplete)

        End If



        If hdr.DisplayName = "Service Code" Then
            Dim ServiceCodeAutoComplete As New AjaxControlToolkit.AutoCompleteExtender
            ServiceCodeAutoComplete.TargetControlID = txt.ID
            ServiceCodeAutoComplete.ServicePath = "~/AJAX/AutoComplete.asmx"
            'ServiceCodeAutoComplete.BehaviorID = "QuickSearchEx"
            ServiceCodeAutoComplete.ServiceMethod = "GetServiceCodes"
            ServiceCodeAutoComplete.MinimumPrefixLength = 1
            ServiceCodeAutoComplete.CompletionInterval = 200
            ServiceCodeAutoComplete.CompletionSetCount = 10
            ServiceCodeAutoComplete.CompletionListItemCssClass = "autocomplete_listItemSP"
            ServiceCodeAutoComplete.CompletionListCssClass = "autocomplete_completionListElementSP"
            ServiceCodeAutoComplete.CompletionListHighlightedItemCssClass = "autocomplete_highlightedListItemSP"


            txt.Parent.Controls.Add(ServiceCodeAutoComplete)
        End If
        
    End Sub

    Public Function GetRowText(ByVal rowNumber As Object) As String
        If CInt(rowNumber) = -1 Then
            Return ""
        Else
            Return rowNumber.ToString()
        End If
    End Function


    Private Sub AddJavaScriptStatements()
        Dim statement As String

        For iList As Integer = 0 To FormulaList.Count - 1
            statement = FormulaList(iList)
            For iPairing As Integer = 0 To FormulaPairings.Count - 1
                Dim pair As FormulaPairing = FormulaPairings(iPairing)
                statement = statement.Replace(pair.DisplayName, pair.TextBoxClientId)
            Next
            statement = statement.Replace("If(", "ExcelIF(")
            statement = statement.Replace("IF(", "ExcelIF(")
            statement = statement.Replace("if(", "ExcelIF(")
            Dim ExcelIfIndex = statement.IndexOf("ExcelIF")
            If ExcelIfIndex > 0 Then
                Dim beforeStatement As String = statement.Substring(0, ExcelIfIndex)
                Dim afterStatement As String = statement.Substring(ExcelIfIndex).Replace("=", "==")
                statement = String.Concat(beforeStatement, afterStatement)
            Else
                'Dim beforeStatement As String = ""
                'Dim afterStatement As String = ""
                'Dim equalIndex As Integer = statement.IndexOf("=")
                'If equalIndex >= 0 Then
                'beforeStatement = statement.Substring(0, equalIndex)
                ''afterStatement = String.Concat("=EvaluateValue(", statement.Substring(equalIndex + 1), ")")
                'statement = String.Concat(beforeStatement, afterStatement)
                'End If


            End If
            If (JavaScriptList Is Nothing) Then
                JavaScriptList = New ArrayList()
            End If

            JavaScriptList.Add(statement)
        Next

    End Sub

    Private Function AddItemsToRows(ByVal itemList As List(Of SpendingPlanItem)) As ArrayList
        Dim CategoryRowList As New Hashtable()
        Dim returnArrayList As New ArrayList()
        Dim newRow As SpendingPlanRow
        Dim rowNumber As Integer

        For i As Integer = 0 To itemList.Count - 1
            rowNumber = itemList(i).BudgetItemNumber
            If Not CategoryRowList.ContainsKey(rowNumber) Then
                newRow = New SpendingPlanRow()
                newRow.RowNumber = rowNumber
                newRow.ItemList = New List(Of SpendingPlanItem)
                CategoryRowList.Add(rowNumber, newRow)
                'SpendingPlanRowList.Add(rowNumber, newRow)
                returnArrayList.Add(newRow)
            Else
                newRow = CategoryRowList.Item(rowNumber)
            End If
            newRow.ItemList.Add(itemList(i))
        Next

        Return returnArrayList

    End Function

    Protected Sub SaveButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SaveButton.Click
        SaveSpendingPlanItems(False)
    End Sub

    Private Sub SaveSpendingPlanItems(ByVal isSubmit As Boolean)
        Dim rowNumber As Integer
        Dim headerId As Integer

        Dim itemTransaction As New Gentle.Framework.Transaction()
        Try

            Dim saveTime As DateTime = DateTime.Now
            For iCategory As Integer = 0 To Me.CategoryDataList.Items.Count - 1
                Dim CategoryRows As Repeater = CategoryDataList.Items(iCategory).FindControl("CategoryRowsRepeater")
                If Not CategoryRows Is Nothing Then
                    For iCategoryRow As Integer = 0 To CategoryRows.Items.Count - 1
                        Dim rowLabel As Label = CategoryRows.Items(iCategoryRow).FindControl("RowNumberLabel")
                        If isRow(rowLabel) Then
                            rowNumber = CInt(rowLabel.Text)
                            Dim RowItems As Repeater = CategoryRows.Items(iCategoryRow).FindControl("RowItemsRepeater")
                            For iItem As Integer = 0 To RowItems.Items.Count - 1
                                Dim itemTextBox As TextBox = RowItems.Items(iItem).FindControl("ItemTextBox")
                                headerId = CInt(itemTextBox.ToolTip)
                                Dim saveItem As SpendingPlanItem = New SpendingPlanItem()
                                saveItem.BudgetItemNumber = rowNumber
                                saveItem.SpendingPlanId = Me.SpendingPlanId
                                saveItem.ItemValue = itemTextBox.Text
                                saveItem.BudgetCategoryHeaderId = headerId
                                saveItem.LastModified = UserAuthorization.CurrentUser.LogonId
                                saveItem.DateModified = saveTime
                                saveItem.Persist(itemTransaction)
                            Next

                        End If
                    Next
                End If
            Next

            itemTransaction.Commit()
            Me.PopupMessage1.ShowSuccessMessage("Spending Plan has been saved.")
            SpendingPlanItem.CleanUpIncompleteItems(Me.SpendingPlanId)

            If isSubmit Then
                Dim updatePlan As SpendingPlan = SpendingPlan.Retrieve(Me.SpendingPlanId)
                updatePlan.LastModified = UserAuthorization.CurrentUser.LogonId
                updatePlan.DateModified = saveTime
                updatePlan.SpendingPlanStatusId = LuSpendingPlanStatus.SpendingPlanStatus.Submitted
                updatePlan.Persist()
                Dim currentParticipantId As Integer = EntityController.GetParticipant().ParticipantId
                EntityController.SendNotification(Cdm.DataCore.CaseNotes.Notification.NotificationType.SpendingPlanSubmittedForApproval, currentParticipantId)
                Response.Write("<script language='javascript'>window.close();</script>")
            End If

        Catch ex As Exception
            itemTransaction.Rollback()
            PopupMessage1.ShowErrorMessage("There was an error saving the Spending Plan Items", ex.Message)
            'If Not ex.InnerException Is Nothing Then
            ' Response.Write("<BR><BR>")
            ' Response.Write(ex.InnerException.Message)
            'End If
        End Try
    End Sub

    Private Function isRow(ByVal rowLabel As Label) As Boolean
        If rowLabel Is Nothing Then Return False
        If IsNumeric(rowLabel.Text) Then
            Return True
        Else
            Return False
        End If
    End Function

    Protected Sub GetSpendingPlanButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles GetSpendingPlanButton.Click
        'These are the option values in the SpendingPlanOption radio button list

        If Me.SpendingPlanOption.SelectedValue.Equals(C_COPY_AND_CREATE) And _
            Me.SpendingPlanDropDownList.SelectedValue = "0" Then
            PopupMessage1.ShowErrorMessage("Incorrect Options Selected", "To copy an existing plan, please select a plan from the dropdown.")
            Exit Sub
        End If

        If Me.SpendingPlanOption.SelectedValue.Equals(C_EDIT_EXISTING) Then
            Me.SpendingPlanId = CInt(Me.SpendingPlanDropDownList.SelectedValue)
            If Me.SpendingPlanId = 0 Then
                PopupMessage1.ShowErrorMessage("Incorrect Options Selected", "To edit an existing plan, please select a plan from the dropdown.")
                Exit Sub
            End If
            Dim editPlan As SpendingPlan = SpendingPlan.Retrieve(Me.SpendingPlanId)
            'Verify that we are only looking at spending plans with DRAFTED status
            If editPlan.SpendingPlanStatusId <> LuSpendingPlanStatus.SpendingPlanStatus.Drafted Then
                PopupMessage1.ShowErrorMessage("Incorrect Options Selected.", "You may only select 'Edit this Plan' for spending plans whose status is 'Drafted.'")
                Exit Sub
            End If
            Dim budgetId As Integer = editPlan.BudgetId
            Dim currentBudget As Budget = Budget.Retrieve(budgetId)
            Me.BudgetAmountTextBox.Text = currentBudget.BudgetAmount.ToString("0.00")


        Else
            If Not VerifyDates() Then
                Exit Sub

            End If
        End If

        SpendingPlanItem.CleanUpIncompleteItems(Me.SpendingPlanId)
        BindCategoryList()
        Me.SpendingPlanAccordion.SelectedIndex = 1
    End Sub

    Private Function VerifyDates() As Boolean
        Dim participantId As Integer = EntityController.GetParticipant().ParticipantId
        Dim selectedSpendingPlanId As Integer = CInt(SpendingPlanDropDownList.SelectedValue)

        '-------------------------------------------------
        ' Part One: verify that dates entered are valid
        '-------------------------------------------------
        If Not IsDate(Me.StartDateTextBox.Text) Or _
           Not IsDate(Me.EndDateTextBox.Text) Then
            Me.PopupMessage1.ShowErrorMessage("Invalid Entry", "Please enter a valid start date and end date.")
            Return False
        Else
            If CDate(EndDateTextBox.Text) < CDate(StartDateTextBox.Text) Then
                Me.PopupMessage1.ShowErrorMessage("Invalid Entry", "End Date can not be earlier than start date.")
                Return False
            End If
        End If
        '-----------------------------------------------------------------------------
        ' Part Two: Verify that a budget is selected whose dates are outside the newly
        ' selected date range
        ' ----------------------------------------------------------------------------

        Dim spendplanStartDate As DateTime = CDate(StartDateTextBox.Text)
        Dim spendplanEndDate As DateTime = CDate(EndDateTextBox.Text)
        Dim budgetId As Integer = 0
        If String.IsNullOrEmpty(BudgetDropDownList.SelectedValue) Then
            Me.PopupMessage1.ShowErrorMessage("Can Not download Spending Plan", "No Budget Selected.")
            Return False
        Else
            budgetId = CInt(BudgetDropDownList.SelectedValue)
            Dim selectedBudget As Budget = Budget.Retrieve(budgetId)
            If selectedBudget.EffectiveDate > spendplanStartDate Or _
               selectedBudget.ExpirationDate < spendplanEndDate Then
                Me.PopupMessage1.ShowErrorMessage("Invalid Entry", "Spending Plan Dates must be within the Budget date range of " + selectedBudget.BudgetPeriodDescription)
                Return False
            End If
            Me.BudgetAmountTextBox.Text = selectedBudget.BudgetAmount.ToString("0.00")
        End If
        Dim errorMessage As String
        Dim versionNumber As Integer
        Dim response As SpendingPlan.DateValidationType = SpendingPlan.CheckDatesValid(participantId, 0, spendplanStartDate, spendplanEndDate, 17001, errorMessage, versionNumber)
        If response = SpendingPlan.DateValidationType.DatesOverlap Or _
        response = SpendingPlan.DateValidationType.ErrorOccurred Then
            Me.PopupMessage1.ShowErrorMessage("Invalid Spending Plan Dates", errorMessage)
            Return False
        End If

        Dim logonId As String = UserAuthorization.CurrentUser.LogonId
        Dim newSpendingPlan As New SpendingPlan()
        newSpendingPlan.BudgetId = budgetId
        newSpendingPlan.StartDate = spendplanStartDate
        newSpendingPlan.EndDate = spendplanEndDate
        newSpendingPlan.Version = versionNumber
        newSpendingPlan.SpendingPlanStatusId = LuSpendingPlanStatus.SpendingPlanStatus.Drafted
        newSpendingPlan.LastModified = logonId
        newSpendingPlan.DateCreated = DateTime.Now
        newSpendingPlan.CreatedBy = logonId
        newSpendingPlan.DateModified = newSpendingPlan.DateCreated
        newSpendingPlan.Persist()
        SpendingPlanItem.CopySpendingPlanItems(selectedSpendingPlanId, newSpendingPlan.SpendingPlanId, logonId)
        Me.SpendingPlanId = newSpendingPlan.SpendingPlanId
        Return True
    End Function

    Protected Sub SpendingPlanOption_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles SpendingPlanOption.SelectedIndexChanged
        Me.SpendingPlanDropDownList.Enabled = True

        Dim showBudgetAndDateRows As Boolean = False

        Select SpendingPlanOption.SelectedValue
            Case C_COPY_AND_CREATE
                showBudgetAndDateRows = True
            Case C_CREATE_BLANK
                showBudgetAndDateRows = True
                Me.SpendingPlanDropDownList.SelectedIndex = 0
                Me.SpendingPlanDropDownList.Enabled = False
            Case C_EDIT_EXISTING
                Dim editPlan As SpendingPlan = SpendingPlan.Retrieve(SpendingPlanDropDownList.SelectedValue)
                If editPlan.SpendingPlanStatusId <> LuSpendingPlanStatus.SpendingPlanStatus.Drafted Then
                    PopupMessage1.ShowErrorMessage("Invalid Selection", "You may only select 'Edit this Plan' for spending plans in 'Drafted' status.")
                End If
        End Select
        SetBudgetAndDateRowsVisible(showBudgetAndDateRows)
    End Sub
    Private Sub SetBudgetAndDateRowsVisible(ByVal isVisible As Boolean)
        selectionRow1.Visible = isVisible
        selectionRow2.Visible = isVisible
        'selectionRow3.Visible = isVisible
        selectionRowHeader.Visible = isVisible
    End Sub

    Protected Sub CancelButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CancelButton.Click

    End Sub

    Protected Sub SubmitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SubmitButton.Click
        SaveSpendingPlanItems(True)
    End Sub
End Class


Public Class SpendingPlanRow
    Private rowNumberValue As Integer
    Private itemListValue As List(Of SpendingPlanItem)

    Public Property RowNumber() As Integer
        Get
            Return rowNumberValue
        End Get
        Set(ByVal value As Integer)
            rowNumberValue = value
        End Set
    End Property

    Public ReadOnly Property RowNumberDisplay() As String
        Get
            If RowNumber = -1 Then
                Return ""
            Else
                Return RowNumber.ToString()
            End If
        End Get
    End Property
    Public Property ItemList() As List(Of SpendingPlanItem)
        Get
            If itemListValue Is Nothing Then
                itemListValue = New List(Of SpendingPlanItem)
            End If
            Return itemListValue
        End Get
        Set(ByVal value As List(Of SpendingPlanItem))
            itemListValue = value
        End Set
    End Property

    Public Sub New()

    End Sub
End Class

Public Class FormulaPairing
    Public DisplayName As String
    Public TextBoxClientId As String

    Public Sub New(ByVal displayNameValue As String, ByVal textBoxClientIdValue As String)
        DisplayName = displayNameValue
        TextBoxClientId = textBoxClientIdValue
    End Sub
End Class



